package logic

import (
	"context"
	"database/sql"
	"fmt"

	"mail/service/account/rpc/account"
	"mail/service/receipt/model"
	"mail/service/receipt/rpc/internal/svc"
	"mail/service/receipt/rpc/receipt"

	"github.com/dtm-labs/dtmgrpc"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"google.golang.org/grpc/status"
)

type ConceptLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewConceptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConceptLogic {
	return &ConceptLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ConceptLogic) Concept(in *receipt.ConceptRequest) (*receipt.ConceptResponse, error) {
	// todo: add your logic here and delete this line
	db, err := sqlx.NewMysql(l.svcCtx.Config.Mysql.DataSource).RawDB()
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//获得子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	//开启子事务屏障
	if err := barrier.CallWithDB(db, func(tx *sql.Tx) error {
		//查询用户是否存在
		_, err := l.svcCtx.AccountRpc.Particular(l.ctx, &account.ParticularRequest{Id: in.Uid})
		if err != nil {
			return fmt.Errorf("account isn't exists.")
		}

		// 适当的、恰当的
		appropriate := model.Receipt{
			Uid:    in.Uid,
			Pid:    in.Pid,
			Amount: in.Amount,
			Status: 0,
		}

		_, err = l.svcCtx.ReceiptModel.TxInsert(tx, &appropriate)
		if err != nil {
			return fmt.Errorf("receipt isn't exists.")
		}
		return nil
	}); err != nil {
		return nil, status.Error(500, err.Error())
	}

	return &receipt.ConceptResponse{}, nil
}
